<template>
  <view class="profile-edit-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-content">
        <text class="title">编辑资料</text>
        <text class="subtitle">更新您的个人信息</text>
      </view>
    </view>

    <!-- 头像上传 -->
    <view class="avatar-section">
      <view class="avatar-wrapper">
        <image
          class="avatar"
          :src="formData.avatar || '/static/images/default-avatar.png'"
          mode="aspectFill"
        ></image>
        <view class="avatar-overlay" @click="chooseAvatar">
          <text class="overlay-text">更换头像</text>
        </view>
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="form-section">
      <view class="form-card">
        <view class="form-item">
          <text class="form-label">昵称</text>
          <input
            v-model="formData.nickname"
            placeholder="请输入昵称"
            type="text"
            class="form-input"
            :disabled="loading"
            maxlength="20"
          />
          <text class="input-count">{{ formData.nickname.length }}/20</text>
        </view>

        <view class="form-item">
          <text class="form-label">邮箱</text>
          <input
            v-model="formData.email"
            placeholder="请输入邮箱地址"
            type="email"
            class="form-input"
            :disabled="loading"
          />
        </view>

        <view class="form-item">
          <text class="form-label">手机号</text>
          <input
            v-model="formData.phone"
            placeholder="请输入手机号码"
            type="tel"
            class="form-input"
            :disabled="loading"
            maxlength="11"
          />
        </view>

        <view class="form-item">
          <text class="form-label">部门</text>
          <picker
            @change="onDepartmentChange"
            :value="departmentIndex"
            :range="departments"
            :disabled="loading"
          >
            <view class="picker-input">
              <text class="picker-text">{{ formData.department || '请选择部门' }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="form-label">个人简介</text>
          <textarea
            v-model="formData.bio"
            placeholder="简单介绍一下自己（选填）"
            class="form-textarea"
            :disabled="loading"
            maxlength="200"
            auto-height
          ></textarea>
          <text class="textarea-count">{{ formData.bio.length }}/200</text>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-section">
      <button
        @click="handleSubmit"
        :disabled="loading || !canSubmit"
        class="btn btn-primary"
        :class="{ 'btn-disabled': loading || !canSubmit }"
      >
        <text class="btn-text">{{ loading ? '保存中...' : '保存修改' }}</text>
      </button>

      <button
        @click="goBack"
        :disabled="loading"
        class="btn btn-secondary"
      >
        <text class="btn-text">取消</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/src/store/user'

// 用户存储
const userStore = useUserStore()

// 表单数据
const formData = ref({
  nickname: '',
  email: '',
  phone: '',
  department: '',
  bio: '',
  avatar: ''
})

const loading = ref(false)
const departmentIndex = ref(0)

// 部门选项
const departments = [
  '技术部',
  '运营部',
  '维护部',
  '客服部',
  '管理部',
  '其他'
]

// 表单验证
const canSubmit = computed(() => {
  return formData.value.nickname.trim() !== '' &&
         (formData.value.email === '' || isValidEmail(formData.value.email)) &&
         (formData.value.phone === '' || isValidPhone(formData.value.phone))
})

// 邮箱验证
const isValidEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

// 手机号验证
const isValidPhone = (phone: string): boolean => {
  const phoneRegex = /^1[3-9]\d{9}$/
  return phoneRegex.test(phone)
}

// 部门选择变化
const onDepartmentChange = (e: any) => {
  departmentIndex.value = e.detail.value
  formData.value.department = departments[e.detail.value]
}

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      // 这里应该上传头像到服务器
      formData.value.avatar = res.tempFilePaths[0]
      uni.showToast({
        title: '头像选择成功',
        icon: 'success'
      })
    },
    fail: () => {
      uni.showToast({
        title: '头像选择失败',
        icon: 'none'
      })
    }
  })
}

// 提交处理
const handleSubmit = async () => {
  if (loading.value || !canSubmit.value) return

  // 验证邮箱
  if (formData.value.email && !isValidEmail(formData.value.email)) {
    uni.showToast({
      title: '请输入有效的邮箱地址',
      icon: 'none'
    })
    return
  }

  // 验证手机号
  if (formData.value.phone && !isValidPhone(formData.value.phone)) {
    uni.showToast({
      title: '请输入有效的手机号码',
      icon: 'none'
    })
    return
  }

  try {
    loading.value = true

    // 调用更新用户信息API
    const success = await userStore.updateUserInfo(formData.value)

    if (success) {
      uni.showToast({
        title: '资料更新成功',
        icon: 'success'
      })

      // 延迟返回
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }

  } catch (error: any) {
    uni.showToast({
      title: error.message || '资料更新失败',
      icon: 'none'
    })
    console.error('资料更新失败:', error)
  } finally {
    loading.value = false
  }
}

// 返回
const goBack = () => {
  uni.navigateBack()
}

// 加载用户信息
onMounted(() => {
  if (userStore.user) {
    formData.value = {
      nickname: userStore.user.nickname || '',
      email: userStore.user.email || '',
      phone: userStore.user.phone || '',
      department: userStore.user.department || '',
      bio: userStore.user.bio || '',
      avatar: userStore.user.avatar || ''
    }

    // 设置部门索引
    const deptIndex = departments.indexOf(formData.value.department)
    if (deptIndex !== -1) {
      departmentIndex.value = deptIndex
    }
  }
})
</script>

<style lang="scss" scoped>
.profile-edit-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f6ffed 0%, #e6f7ff 100%);
  padding-bottom: 40rpx;
}

// 页面头部
.page-header {
  background: linear-gradient(135deg, #52c41a, #73d13d);
  padding: 48rpx 32rpx 32rpx;
  color: #ffffff;

  .header-content {
    text-align: center;
  }

  .title {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 8rpx;
  }

  .subtitle {
    font-size: 26rpx;
    opacity: 0.9;
  }
}

// 头像区域
.avatar-section {
  padding: 48rpx 32rpx;
  text-align: center;

  .avatar-wrapper {
    position: relative;
    display: inline-block;

    .avatar {
      width: 160rpx;
      height: 160rpx;
      border-radius: 80rpx;
      border: 4rpx solid rgba(82, 196, 26, 0.2);
      background: #f8f9fa;
    }

    .avatar-overlay {
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      background: rgba(0, 0, 0, 0.7);
      color: #ffffff;
      padding: 8rpx 16rpx;
      border-radius: 16rpx;
      font-size: 24rpx;

      .overlay-text {
        font-weight: 500;
      }
    }
  }
}

// 表单区域
.form-section {
  padding: 0 32rpx;

  .form-card {
    background: #ffffff;
    border-radius: 24rpx;
    padding: 32rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .form-item {
      margin-bottom: 32rpx;
      position: relative;

      &:last-child {
        margin-bottom: 0;
      }

      .form-label {
        display: block;
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        margin-bottom: 12rpx;
      }

      .form-input {
        width: 100%;
        height: 88rpx;
        padding: 0 24rpx;
        border: 2rpx solid #e8e8e8;
        border-radius: 12rpx;
        font-size: 30rpx;
        background: #fafafa;
        transition: all 0.3s ease;

        &:focus {
          border-color: #52c41a;
          background: #ffffff;
          box-shadow: 0 0 0 4rpx rgba(82, 196, 26, 0.1);
        }
      }

      .input-count {
        position: absolute;
        right: 24rpx;
        top: 50%;
        transform: translateY(-50%);
        font-size: 24rpx;
        color: #999;
      }

      .picker-input {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 88rpx;
        padding: 0 24rpx;
        border: 2rpx solid #e8e8e8;
        border-radius: 12rpx;
        background: #fafafa;
        transition: all 0.3s ease;

        &:active {
          border-color: #52c41a;
        }

        .picker-text {
          font-size: 30rpx;
          color: #333;
        }

        .picker-arrow {
          font-size: 28rpx;
          color: #999;
        }
      }

      .form-textarea {
        width: 100%;
        min-height: 120rpx;
        padding: 24rpx;
        border: 2rpx solid #e8e8e8;
        border-radius: 12rpx;
        font-size: 30rpx;
        background: #fafafa;
        transition: all 0.3s ease;
        resize: none;

        &:focus {
          border-color: #52c41a;
          background: #ffffff;
          box-shadow: 0 0 0 4rpx rgba(82, 196, 26, 0.1);
        }
      }

      .textarea-count {
        position: absolute;
        right: 24rpx;
        bottom: 24rpx;
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

// 操作按钮
.action-section {
  padding: 0 32rpx;
  margin-top: 48rpx;

  .btn {
    width: 100%;
    height: 88rpx;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 24rpx;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
    }

    &.btn-primary {
      background: linear-gradient(135deg, #52c41a, #73d13d);
      box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);

      &.btn-disabled {
        background: #ccc;
        box-shadow: none;
        transform: none;
      }

      .btn-text {
        font-size: 32rpx;
        color: #ffffff;
        font-weight: 500;
      }
    }

    &.btn-secondary {
      background: #ffffff;
      border: 2rpx solid #e8e8e8;

      .btn-text {
        font-size: 32rpx;
        color: #666;
        font-weight: 500;
      }
    }
  }
}
</style>